package com.ylt.controller.pay;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.utils.tfzf.Kv;
import com.utils.ylt.PkeyGenerator;
import com.ylt.dao.mysqldb.ShopChatDao;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Log4JLoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class WxPayHandle {
	
	InternalLogger log = Log4JLoggerFactory.getInstance(WxPayHandle.class);

	@Value("${wx.pub.appid}")
	String wxPubAppId;
	@Value("${wx.lite.appid}")
	String wxLiteAppId;
	//支付异步通知地址
    @Value("${pay.notify-url}")
    private String payNotifyUrl;
    //支付成功后页面回跳地址
    @Value("${pay.return-url}")
    private String payReturnUrl;
    //支付未完成时用户返回地址
    @Value("${pay.show-url}")
    private String payShowUrl;
	
	public Kv doRecodPay(JSONObject jsonObject,PageInfo order_lines,ShopChatDao shopChatDao,String requestIp) {
		log.debug("jsonObject===>"+jsonObject.toJSONString());
		log.debug("order_lines===>"+JSONUtil.toJsonStr(order_lines));
		Kv mergePayResult=null;
		try {
			if(order_lines.getList().size()==0) {
				return null;
			}
			if(!jsonObject.containsKey("SHOP_CUST_ID")||!jsonObject.containsKey("B2B_ORDER_NUMBER")||!jsonObject.containsKey("transChannel")||!jsonObject.containsKey("openId")) {
				return null;
			}
			Map payHeader = (Map) order_lines.getList().get(0);
			String shop_cust_id=jsonObject.get("SHOP_CUST_ID").toString();
			String b2b_order_number=jsonObject.get("B2B_ORDER_NUMBER").toString();
			String transChannel = jsonObject.getString("transChannel");
			String SUB_OPENID=jsonObject.getString("openId");
			//根据店铺查询特约商户号
			Map mchMap = new HashMap();
			mchMap.put("SHOP_CUST_ID", shop_cust_id);
			List listmch  = shopChatDao.selectMerchant(mchMap);//根据店铺id获取商户的信息；
			if(listmch!=null && listmch.size()>0) {
				mchMap = (Map) listmch.get(0);
				String u_id = payHeader.get("U_ID").toString();
				String subpartner = mchMap.get("SUBPARTNER").toString();//商户号
				String notify_url = payNotifyUrl;//异步通知路径
				String return_url = payReturnUrl+b2b_order_number;//同步通知路径
				String show_url = payShowUrl+b2b_order_number;//商户展示路径

				Kv params = Kv.create()
						.set("subpartner", subpartner)//特约商户号
						.set("outTradeNo", b2b_order_number)//商户订单号
						.set("subject", "订单编号"+b2b_order_number)//商品名称
						.set("body", "订单编号"+b2b_order_number)//商品描述，对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body
						.set("totalFee", payHeader.get("PAY_TOTAL_FEE").toString())
						.set("feeType", 1)//币种，1-人民币，固定值1
						.set("spbillCreateIp", requestIp)
						.setIfNotBlank("attach", shop_cust_id + "|" + b2b_order_number + "|" + u_id)//附加数据，支付完成或查询订单时，将会原样返回，可用来传递自定义数据
						.set("notifyUrl", notify_url)//异步通知地址，由银行在支付完成后，将支付结果异步通知该地址
						.set("returnUrl", return_url)//同步通知地址，处理完请求后，将自动跳转到该地址
						.set("showUrl", show_url)//商品展示网址，当进入天府收银台时，如果用户点击返回，则会跳转至该地址
						.setIfNotBlank("deliveryAddr", "")//订单收货地址
						.setIfNotBlank("tradeMode", "0002")//交易类型，0001-担保支付，0002-即时到账，默认为0002
						.set("transPattern", 0)//交易模式，0-直连模式（直接调整支付渠道网关），1-间连模式（跳转天府支付收银台）， 默认模式为0
						.set("transChannel", transChannel)//支付渠道
						.setIfNotBlank("deviceInfo", "");
				if (transChannel == null || "wx_lite".equals(transChannel)) {
					params.set("wxLite",
							Kv.create()
									.set("subAppId", wxLiteAppId)//商户小程序账号ID
									.set("subOpenid", SUB_OPENID)//商户小程序openID
									.set("qrReturnType", 1)//二维码返回方式，0-二维码图片BASE64字符串，1-二维码图片URL，默认为0
					);
				} else if ("wx_pub".equals(transChannel)) {
					params.set("wxPub",
							Kv.create()
									.set("subAppId", wxPubAppId)//商户公众账号ID
									.set("subOpenid", SUB_OPENID)//商户公众账号openID
									.set("qrReturnType", 1)//二维码返回方式，0-二维码图片BASE64字符串，1-二维码图片URL，默认为0
					);
				}
				mergePayResult = com.utils.tfzf.Api.mergePay(params);
				mergePayResult.put("outTradeNo", params.get("outTradeNo"));
				String transactionId = mergePayResult.getStr("transactionId");
				if (mergePayResult.getBoolean("status")) {
					JSONObject jo = JSONObject.parseObject(mergePayResult.getStr("returnMsg"));
					String qrcode = jo.getString("qr_code");
					String kv[] = qrcode.split("&");
					for (int i = 0; i < kv.length; i++) {
						String da[] = kv[i].split("=", 2);
						mergePayResult.put(da[0], da[1]);
					}
					//插入YH_PAY_ORDER_HEADER
					payHeader.put("OUT_TRANSNO", mergePayResult.getStr("outTradeNo"));
                    //根据pay订单号判断是否已经生成支付单，如果没有则先插入，否则跳出
					List tempHList = shopChatDao.selectPayHeaderByNo(payHeader);
					if(tempHList==null|| tempHList.size()==0) {
						String hID = PkeyGenerator.getUniqueString();
						payHeader.put("H_ID", hID);
						payHeader.put("SHOP_CUST_ID", shop_cust_id);
						payHeader.put("B2B_ORDER_NUMBER", b2b_order_number);
						payHeader.put("TRANSACTION_ID", transactionId);
						payHeader.put("PAY_TYPE", transChannel);
						payHeader.put("PAY_TOTAL_FEE", "0.01");//pr.get("totalFee"));
						payHeader.put("PAY_ZT", "N");
						payHeader.put("YJ_STATE", "N");
						shopChatDao.insertYH_PAY_ORDER_HEADER(payHeader);

						List pl = order_lines.getList();
						for (int i = 0; i < pl.size(); i++) {
							Map line = (Map) pl.get(i);
							line.put("LINE_ID", com.utils.PkeyGenerator.getUniqueString());
							//插入YH_PAY_ORDER_LINE
							line.put("H_ID", hID);
							line.put("TRANSACTION_ID", transactionId);
							line.put("PAY_SL", line.get("ORDER_QTY"));
							line.put("PAY_JE", line.get("LINE_HSJE"));//实际支付金额，暂时取订单金额
							line.put("ORDER_ZJE", line.get("LINE_HSJE"));//订单金额
							line.put("YWY_OPENID", SUB_OPENID);//取付款人openid
							line.put("PAY_ZT", "N");
							line.put("YJ_STATE", "N");
							shopChatDao.insertYH_PAY_ORDER_LINE(line);
						}
					}
					mergePayResult.put("state", 1);
				} else {
					mergePayResult.put("state", 0);
				}
			}
		}catch(Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return mergePayResult;
	}

}
